// ===== 反馈管理系统 =====

let allFeedbacks = [];
let filteredFeedbacks = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadFeedbacks();
    updateStatistics();
    renderFeedbacks();
    setupEventListeners();
});

// ===== 数据加载和处理 =====

function loadFeedbacks() {
    try {
        const feedbackData = localStorage.getItem('modFeedbacks');
        allFeedbacks = feedbackData ? JSON.parse(feedbackData) : [];
        filteredFeedbacks = [...allFeedbacks];
        
        // 按时间倒序排列（最新的在前）
        allFeedbacks.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
        filteredFeedbacks.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
        
        console.log('已加载反馈数据:', allFeedbacks.length, '条');
    } catch (error) {
        console.error('加载反馈数据失败:', error);
        allFeedbacks = [];
        filteredFeedbacks = [];
    }
}

function updateStatistics() {
    const totalFeedbacks = allFeedbacks.length;
    const bugReports = allFeedbacks.filter(f => f.type === 'bug').length;
    const featureRequests = allFeedbacks.filter(f => f.type === 'feature').length;
    
    // 计算今日新增
    const today = new Date().toDateString();
    const todayFeedbacks = allFeedbacks.filter(f => {
        const feedbackDate = new Date(f.timestamp).toDateString();
        return feedbackDate === today;
    }).length;
    
    // 更新统计显示
    document.getElementById('totalFeedbacks').textContent = totalFeedbacks;
    document.getElementById('bugReports').textContent = bugReports;
    document.getElementById('featureRequests').textContent = featureRequests;
    document.getElementById('todayFeedbacks').textContent = todayFeedbacks;
    
    // 添加动画效果
    animateNumbers();
}

function animateNumbers() {
    const counters = document.querySelectorAll('.stat-number');
    counters.forEach(counter => {
        const target = parseInt(counter.textContent);
        const increment = Math.max(1, Math.floor(target / 20));
        let current = 0;
        
        const updateCounter = () => {
            if (current < target) {
                current = Math.min(current + increment, target);
                counter.textContent = current;
                requestAnimationFrame(updateCounter);
            }
        };
        
        counter.textContent = '0';
        setTimeout(updateCounter, 200);
    });
}

// ===== 渲染功能 =====

function renderFeedbacks() {
    const feedbackList = document.getElementById('feedbackList');
    
    if (filteredFeedbacks.length === 0) {
        feedbackList.innerHTML = `
            <div class="no-feedback">
                <i class="fas fa-inbox"></i>
                <h3>暂无反馈数据</h3>
                <p>还没有用户提交反馈，或者当前筛选条件下没有匹配的结果。</p>
            </div>
        `;
        return;
    }
    
    feedbackList.innerHTML = filteredFeedbacks.map((feedback, index) => 
        createFeedbackHTML(feedback, index)
    ).join('');
    
    // 添加展开/收起事件监听
    setupFeedbackEvents();
}

function createFeedbackHTML(feedback, index) {
    const formatDate = (timestamp) => {
        const date = new Date(timestamp);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    };
    
    const getTypeClass = (type) => {
        const typeMap = {
            'bug': 'type-bug',
            'feature': 'type-feature',
            'compatibility': 'type-compatibility',
            'other': 'type-other'
        };
        return typeMap[type] || 'type-other';
    };
    
    const getTypeName = (type) => {
        const typeNames = {
            'bug': 'Bug报告',
            'feature': '功能建议',
            'compatibility': '兼容性问题',
            'other': '其他问题'
        };
        return typeNames[type] || '未知类型';
    };
    
    return `
        <div class="feedback-item" data-index="${index}">
            <div class="feedback-header" onclick="toggleFeedback(${index})">
                <div class="feedback-info">
                    <h3 class="feedback-title">${escapeHtml(feedback.title)}</h3>
                    <div class="feedback-meta">
                        <span class="feedback-type ${getTypeClass(feedback.type)}">
                            ${getTypeName(feedback.type)}
                        </span>
                        <div class="meta-item">
                            <i class="fas fa-envelope"></i>
                            ${escapeHtml(feedback.email)}
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-clock"></i>
                            ${formatDate(feedback.timestamp)}
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-cube"></i>
                            MC ${feedback.minecraftVersion} / ${feedback.modVersion}
                        </div>
                        <div class="meta-item">
                            <i class="fas fa-globe"></i>
                            ${feedback.language === 'zh' ? '中文' : 'English'}
                        </div>
                    </div>
                </div>
                <i class="fas fa-chevron-down feedback-toggle"></i>
            </div>
            
            <div class="feedback-content">
                <div class="content-grid">
                    <div class="content-section">
                        <div class="section-title">
                            <i class="fas fa-align-left"></i>
                            问题描述
                        </div>
                        <div class="section-content">${escapeHtml(feedback.description)}</div>
                    </div>
                    
                    ${feedback.reproduction ? `
                    <div class="content-section">
                        <div class="section-title">
                            <i class="fas fa-list-ol"></i>
                            重现步骤
                        </div>
                        <div class="section-content">${escapeHtml(feedback.reproduction)}</div>
                    </div>
                    ` : ''}
                    
                    ${feedback.otherMods ? `
                    <div class="content-section">
                        <div class="section-title">
                            <i class="fas fa-puzzle-piece"></i>
                            其他模组
                        </div>
                        <div class="section-content">${escapeHtml(feedback.otherMods)}</div>
                    </div>
                    ` : ''}
                    
                    <div class="content-section">
                        <div class="section-title">
                            <i class="fas fa-info-circle"></i>
                            技术信息
                        </div>
                        <div class="section-content">
                            问题类型: ${getTypeName(feedback.type)}
                            Minecraft版本: ${feedback.minecraftVersion}
                            模组版本: ${feedback.modVersion}
                            提交时间: ${formatDate(feedback.timestamp)}
                            界面语言: ${feedback.language === 'zh' ? '中文' : 'English'}
                        </div>
                    </div>
                </div>
                
                <div class="feedback-actions">
                    <button class="btn btn-primary btn-small" onclick="copyFeedback(${index})">
                        <i class="fas fa-copy"></i>
                        复制内容
                    </button>
                    <button class="btn btn-secondary btn-small" onclick="emailReply('${escapeHtml(feedback.email)}')">
                        <i class="fas fa-reply"></i>
                        邮件回复
                    </button>
                    <button class="btn btn-danger btn-small" onclick="deleteFeedback(${index})">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </div>
        </div>
    `;
}

function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// ===== 事件处理 =====

function setupEventListeners() {
    // 搜索输入实时过滤
    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', debounce(applyFilters, 300));
    
    // 回车键触发搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            applyFilters();
        }
    });
}

function setupFeedbackEvents() {
    // 阻止点击反馈内容时触发折叠
    document.querySelectorAll('.feedback-content').forEach(content => {
        content.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    });
}

function toggleFeedback(index) {
    const feedbackItem = document.querySelector(`[data-index="${index}"]`);
    feedbackItem.classList.toggle('active');
}

// ===== 筛选和搜索 =====

function applyFilters() {
    const typeFilter = document.getElementById('typeFilter').value;
    const dateFilter = document.getElementById('dateFilter').value;
    const versionFilter = document.getElementById('versionFilter').value;
    const searchTerm = document.getElementById('searchInput').value.toLowerCase().trim();
    
    filteredFeedbacks = allFeedbacks.filter(feedback => {
        // 类型筛选
        if (typeFilter !== 'all' && feedback.type !== typeFilter) {
            return false;
        }
        
        // 版本筛选
        if (versionFilter !== 'all' && feedback.modVersion !== versionFilter) {
            return false;
        }
        
        // 时间筛选
        if (dateFilter !== 'all') {
            const feedbackDate = new Date(feedback.timestamp);
            const now = new Date();
            
            switch (dateFilter) {
                case 'today':
                    if (feedbackDate.toDateString() !== now.toDateString()) {
                        return false;
                    }
                    break;
                case 'week':
                    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                    if (feedbackDate < weekAgo) {
                        return false;
                    }
                    break;
                case 'month':
                    const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
                    if (feedbackDate < monthAgo) {
                        return false;
                    }
                    break;
            }
        }
        
        // 关键词搜索
        if (searchTerm) {
            const searchableText = [
                feedback.title,
                feedback.description,
                feedback.email,
                feedback.reproduction || '',
                feedback.otherMods || ''
            ].join(' ').toLowerCase();
            
            if (!searchableText.includes(searchTerm)) {
                return false;
            }
        }
        
        return true;
    });
    
    renderFeedbacks();
    showNotification(`筛选完成，找到 ${filteredFeedbacks.length} 条匹配的反馈`, 'success');
}

function clearFilters() {
    document.getElementById('typeFilter').value = 'all';
    document.getElementById('dateFilter').value = 'all';
    document.getElementById('versionFilter').value = 'all';
    document.getElementById('searchInput').value = '';
    
    filteredFeedbacks = [...allFeedbacks];
    renderFeedbacks();
    showNotification('筛选条件已清除', 'info');
}

// ===== 操作功能 =====

function copyFeedback(index) {
    const feedback = filteredFeedbacks[index];
    const feedbackText = `
反馈类型: ${feedback.type}
问题标题: ${feedback.title}
用户邮箱: ${feedback.email}
MC版本: ${feedback.minecraftVersion}
模组版本: ${feedback.modVersion}
提交时间: ${new Date(feedback.timestamp).toLocaleString()}

问题描述:
${feedback.description}

${feedback.reproduction ? `重现步骤:\n${feedback.reproduction}\n\n` : ''}
${feedback.otherMods ? `其他模组:\n${feedback.otherMods}\n\n` : ''}
    `.trim();
    
    navigator.clipboard.writeText(feedbackText).then(() => {
        showNotification('反馈内容已复制到剪贴板', 'success');
    }).catch(err => {
        console.error('复制失败:', err);
        showNotification('复制失败，请手动选择复制', 'error');
    });
}

function emailReply(email) {
    const subject = encodeURIComponent('关于您的模组反馈');
    const body = encodeURIComponent(`您好，\n\n感谢您提交的反馈。我们已经收到并正在处理您的问题。\n\n此致敬礼\n加强附魔金苹果模组团队`);
    const mailtoLink = `mailto:${email}?subject=${subject}&body=${body}`;
    
    window.open(mailtoLink);
    showNotification('正在打开邮件客户端...', 'info');
}

function deleteFeedback(index) {
    if (confirm('确定要删除这条反馈吗？此操作不可撤销。')) {
        const feedbackToDelete = filteredFeedbacks[index];
        
        // 从原始数组中删除
        const originalIndex = allFeedbacks.findIndex(f => 
            f.timestamp === feedbackToDelete.timestamp && f.email === feedbackToDelete.email
        );
        
        if (originalIndex !== -1) {
            allFeedbacks.splice(originalIndex, 1);
            
            // 更新localStorage
            localStorage.setItem('modFeedbacks', JSON.stringify(allFeedbacks));
            
            // 重新应用筛选
            applyFilters();
            updateStatistics();
            
            showNotification('反馈已删除', 'success');
        }
    }
}

function exportFeedbacks() {
    if (filteredFeedbacks.length === 0) {
        showNotification('没有可导出的反馈数据', 'warning');
        return;
    }
    
    const csvContent = generateCSV(filteredFeedbacks);
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `mod-feedbacks-${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showNotification('反馈数据已导出', 'success');
}

function generateCSV(feedbacks) {
    const headers = ['提交时间', '问题类型', '标题', '邮箱', 'MC版本', '模组版本', '描述', '重现步骤', '其他模组'];
    const rows = feedbacks.map(feedback => [
        new Date(feedback.timestamp).toLocaleString(),
        feedback.type,
        feedback.title,
        feedback.email,
        feedback.minecraftVersion,
        feedback.modVersion,
        feedback.description,
        feedback.reproduction || '',
        feedback.otherMods || ''
    ]);
    
    const csvData = [headers, ...rows];
    return csvData.map(row => 
        row.map(field => `"${String(field).replace(/"/g, '""')}"`).join(',')
    ).join('\n');
}

function clearAllFeedbacks() {
    if (confirm('确定要清空所有反馈数据吗？此操作不可撤销！')) {
        if (confirm('请再次确认：这将永久删除所有反馈数据！')) {
            localStorage.removeItem('modFeedbacks');
            allFeedbacks = [];
            filteredFeedbacks = [];
            renderFeedbacks();
            updateStatistics();
            showNotification('所有反馈数据已清空', 'info');
        }
    }
}

// ===== 工具函数 =====

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = function() {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

function refreshFeedbacks() {
    showNotification('正在刷新反馈列表...', 'info');
    
    setTimeout(() => {
        loadFeedbacks();
        renderFeedbacks();
        updateStatistics();
        showNotification('反馈列表已刷新', 'success');
    }, 1000);
}

function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check' : type === 'error' ? 'times' : 'info'}"></i>
        <span>${message}</span>
    `;
    
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#4ade80' : type === 'error' ? '#ef4444' : type === 'warning' ? '#f59e0b' : '#3b82f6'};
        color: white;
        padding: 15px 20px;
        border-radius: 10px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 300px;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}